package com.cyzy.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * TODO
 *
 * @author Honarly
 * @date 2024.11.18
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${file.upload.url}")
    private String uploadFilePath;

    @Value("${file.upload.maxSize}")
    private Long maxSize;

    @PostMapping("/upload")
    public String httpUpload(@RequestParam("files") MultipartFile files[]){
        JSONObject object=new JSONObject();
        for(int i=0; i<files.length; i++) {
            // 检查文件大小
            if (files[i].getSize() > maxSize) {
                object.put("code", 0);
                object.put("message", "单文件大小超过2MB");
                return object.toString();
            }
        }
        for(int i=0; i<files.length; i++){
            String fileName = files[i].getOriginalFilename();  // 文件名
            // 文件名替换
            String[] split = fileName.split("\\.");
            String newFileName = "";
            if (split.length > 0) {
                // 说明有后缀
                String suffix = split[split.length - 1];
                for (int j = 0; j < split.length - 1; j++) {
                    newFileName += split[j];
                }
                newFileName += "_" + UUID.randomUUID() + "." + suffix;
            }else {
                newFileName = fileName + "_" + UUID.randomUUID();
            }

            File dest = new File(uploadFilePath +'/'+ newFileName);
            object.put("data", "/images/" + uploadFilePath +'/'+ newFileName);
            // 如果文件目录不存在，直接创建
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            try {
                // 写入文件
                files[i].transferTo(dest);
            } catch (Exception e) {
                object.put("code",2);
                object.put("message","程序错误，请重新上传");
                return object.toString();
            }
        }
        object.put("code",1);
        object.put("message","文件上传成功");
        return object.toString();
    }

}
